/**   
  * @Title: RoleTg.java 
  * @package com.sysmanage.permissions.controls 
  * @Description: 
  * @author XXXX@163.com 
  * @date 2011-9-23 下午2:58:37 
  * @version V1.0   
  */

package com.sysmanage.permissions.controls;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sysmanage.common.tools.page.Pagination;
import com.sysmanage.framework.controls.struts2.BaseTg;
import com.sysmanage.permissions.ConstCode;
import com.sysmanage.permissions.model.Groups;
import com.sysmanage.permissions.model.Role;
import com.sysmanage.permissions.model.Users;
import com.sysmanage.permissions.service.ILogService;
import com.sysmanage.permissions.service.IResourcesService;
import com.sysmanage.permissions.service.IRoleService;
import com.sysmanage.permissions.service.IUserService;

/** 
 * @ClassName: RoleTg 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author XXXX@163.com
 * @date 2011-9-23 下午2:58:37 
 *  
 */
@SuppressWarnings("serial")
@Scope("prototype")
@Controller(value="permissions.roleTgControl")
public class RoleTg extends BaseTg {
	@Autowired
	private ILogService logService;
	/** 
	  * @Fields roleService : 角色服务接口
	  */ 
	@Resource(name="roleService")
	private IRoleService roleService;

	@Autowired
	private IUserService userService;	
	/** 
	  * @Fields resourcesService : 资源服务接口
	  */ 
	@Autowired
	private IResourcesService resourcesService;
	
	
	//审批的参数
	private String authIds;

	private String authFlowId;
	private String authUser;
	
	/** 
	  * @Title: index 
	  * @Description:角色信息模块索引函数
	  * @param @return
	  * @return String
	  * @throws 
	  */
	public String index(){
		return SUCCESS;
	}
	
	/** 
	  * @Title: getItems 
	  * @Description:获得角色列表 
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getItems(){
		Pagination pagination = this.roleService.getPageList(this.getRole(), page, rows,sort,order);
		List<Role> roleList = pagination.getList();
		JsonConfig config = new JsonConfig();   
		 config.setIgnoreDefaultExcludes(false);      
		 config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);    
//		 config.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd")); //date processor register   
		 config.setExcludes(new String[]{//只要设置这个数组，指定过滤哪些字段。   
		   "resources",
		   "groups",
		   "editResources",
		   "editGroups"
		 }); 
		try {
			outJsonPlainString(response,"{\"total\":" + pagination.getTotalCount() + ",\"rows\":"+JSONSerializer.toJSON(roleList,config).toString() + "}");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	  * @Title: asignToGroups 
	  * @Description: 查看该角色所分配到的组
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void asignToGroups(){
		Role role = roleService.findById(Integer.valueOf(id));
		List<Groups> result = new  ArrayList<Groups>();
		if(role!=null)
		{
			Set<Groups> list = role.getGroups();
			Iterator<Groups> it = list.iterator();
			while(it.hasNext()){
				result.add(it.next());
			}
		}
		JSONArray jsonArray = JSONArray.fromObject(doGroup(result));
		outJsonPlainString(response,jsonArray.toString());
	}	
	/** 
	  * @Title: saveAuthorizate 
	  * @Description: 给指定ID的角色分配资源 
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void saveAuthorizate(){
		try{
			logService.log("修改角色[id:"+id+"]包含的资源["+rids+"]", "修改");
			this.roleService.saveAuthorizate(id,rids);
			outJsonPlainString(response, "{\"success\":true}");
		}catch(Exception e){
			e.printStackTrace();
			outJsonPlainString(response, "{\"error\":true}");
		}
	}
	/** 
	  * @Title: getAllTrees 
	  * @Description:根据角色ID获得获得所有资源树，其中角色有权限的资源checkbox为true  
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getAllTrees(){
		try {
			JSONArray json = JSONArray.fromObject(this.roleService.getAllListTrees(id));
			outJsonString(response,json.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			outJsonPlainString(response,"[]");
		}
	}
	/** 
	  * @Title: save 
	  * @Description:新增一条角色记录 
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void save(){
		logService.log("创建"+role.toString(), "创建");
		if(this.roleService.addRole(role)){
			outJsonPlainString(response, "{\"success\":true}");
		}else{
			outJsonPlainString(response, "{\"error\":true}");
		}
	}
	/** 
	  * @Title: update 
	  * @Description: 修改角色记录 
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void update(){
		logService.log("更新"+role.toString(), "修改");
		if(this.roleService.alter(role)){
			outJsonPlainString(response, "{\"success\":true}");
		}else{
			outJsonPlainString(response, "{\"error\":true}");
		}
		
	}
	/** 
	  * @Title: getActions 
	  * @Description: 获得所有操作信息模块中的记录，做为给角色的资源添加操作页面的第一行
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getActions(){
		try{
			JSONArray json = JSONArray.fromObject(this.roleService.getAllActions());
			outHtmlUTFString(response,json.toString());
		}catch(Exception e){
			outJsonPlainString(response,"[]");
		}
	}
	/** 
	  * @Title: getRAMappings 
	  * @Description:获得当前角色拥有的资源树
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getRAMappings(){
		try {
			Role role = this.roleService.findById(id);
			if(role==null){
				
				outJsonString(response,"[]");
			}
			List list = this.resourcesService.getRoleRAMappings(id,role.getResources());
			JSONArray json = JSONArray.fromObject(list);
			outJsonString(response,json.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			outJsonPlainString(response,"[]");
		}
		
	}
	/** 
	  * @Title: getRAMappings 
	  * @Description:获得当前角色拥有的资源数组
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getResActMappings(){
		try {
			Role role = this.roleService.findById(id);
			if(role==null){
				outJsonString(response,"[]");
			}
			List<Map<String, Object>> list = this.resourcesService.getRoleResActMappings(role);

			JSONArray json = JSONArray.fromObject(list);
			outJsonPlainString(response,"{\"total\":" + list.size() + ",\"rows\":"+json.toString() + "}");
		} catch (Exception e) {
			e.printStackTrace();
			outJsonPlainString(response,"{\"total\":0,\"rows\":[]}");
		}
	}
	/** 
	  * @Title: saveResActions 
	  * @Description:保存用户资源对应的操作 
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void saveResActions(){
		try{
			this.roleService.saveResActions(id, roleActions);
			outJsonPlainString(response, "{\"success\":true}");
		}catch(Exception e){
			
			outJsonPlainString(response, "{\"error\":true}");
		}
	}
	/** 
	  * @Title: delete 
	  * @Description: 删除指定id的角色
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void delete(){
		String message = "";
		boolean ret = true;
		Role role = roleService.findById(Integer.valueOf(id));
		if(role!=null)
		{
			Set<Groups> list = role.getGroups();
			if(list!=null&&list.size()>0)
			{
				ret = false;
				message = "该角色被用户组使用,请先停止使用该角色再进行删除！";
			}
		}
		else
		{
			ret = false;
			message = "角色不存在,可能已被删除!";
		}
		if(!ret)
		{
			outJsonPlainString(response,"{\"error\":\"true\""+",\"message\":\""+message+"\"}");
		}
		else
		{
			if(this.roleService.delete(role)){
				logService.log("删除"+role.toString(), "删除");
				outJsonPlainString(response,"{\"success\":\"true\"}");
			}else{				
				outJsonPlainString(response,"{\"error\":\"true\""+",\"message\":\""+message+"\"}");
			}
		}
	}

	/** 
	  * @Title: doGroup 
	  * @Description: 解决struts2.0domal接受参数的方法
	  * @param @param list 装doGroup的具体信息。
	  * @param @return
	  * @return List
	  * @throws 
	  */
	private List doGroup(List<Groups> list) {
		List lists = new ArrayList();
		if(list != null && list.size() > 0){
			for(int i =0;i<list.size();i++){
				Map<String,String> map = new HashMap<String, String>();
				Groups group = list.get(i);
				map.put("name", group.getName());
				map.put("id", group.getId() + "");
				map.put("memo", group.getMemo());
				lists.add(map);
			}
		}
		return lists;
	}	
	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}
	private Role role;
	private int id;
	private String rids;
	private String roleActions;
	
	public String getRoleActions() {
		return roleActions;
	}

	public void setRoleActions(String roleActions) {
		this.roleActions = roleActions;
	}

	public String getRids() {
		return rids;
	}

	public void setRids(String rids) {
		this.rids = rids;
	}

	/**
	 * @return the role
	 */
	public Role getRole() {
		return role;
	}

	/**
	 * @param role the role to set
	 */
	public void setRole(Role role) {
		this.role = role;
	}
	public String getAuthIds() {
		return authIds;
	}

	public void setAuthIds(String authIds) {
		this.authIds = authIds;
	}

	public String getAuthFlowId() {
		return authFlowId;
	}

	public void setAuthFlowId(String authFlowId) {
		this.authFlowId = authFlowId;
	}

	public String getAuthUser() {
		return authUser;
	}

	public void setAuthUser(String authUser) {
		this.authUser = authUser;
	}	
}
